<template>
    <el-menu router unique-opened ref="navbar"  :default-active="onRoutes"  menu-trigger="click" @select="selectMenu" @open="openMenu" @close="closeMenu">
        <nav-item  v-for="(item, index) in navList"  :item="item" :navIndex="String(index)" :key="index">
        </nav-item>
    </el-menu>
</template>

<script>
import { mapState } from 'vuex';
import navItem from '@/components/navItem/navItem';

export default {
  components: {
    navItem
  },
  data () {
    return {
    };
  },
  computed: {
    ...mapState({
      navList: state => state.auth.navList
    }),
    // 首次进入页面时展开当前页面所属的菜单
    onRoutes () {
      return this.$route.path;
    }
  },
  watch: {
    // 当通过TagNav来激活页面时也执行一次selectMenu
    $route () {
      let path = this.$route.path;
      let indexPath = this.$refs.navbar.items[path].indexPath;
      this.selectMenu(path, indexPath);
    }
  },
  methods: {
    selectMenu (index, indexPath) {
      /**
             * 在选择父级菜单时自动关闭其下所有子菜单
             * 选择时获取点击菜单的父级index，并计算得到该index在已打开菜单中的索引值，
             * 关闭位于当前打开菜单中该索引值之后的全部菜单
             */
      // 获取当前打开的所有菜单
      let openedMenus = this.$refs.navbar.openedMenus;
      let openMenu = openedMenus.slice(0, openedMenus.length - 1);

      // 关闭菜单
      openMenu = openMenu.reverse();
      openMenu.forEach((ele) => {
        this.$refs.navbar.closeMenu(ele);
      });
    },
    openMenu () {
    },
    closeMenu () {
    },
    closeAll () {
      let openMenu = this.$refs.navbar.openedMenus.concat([]);
      openMenu = openMenu.reverse();
      openMenu.forEach((ele) => {
        this.$refs.navbar.closeMenu(ele);
      });
    }
  }
};
</script>
